package com.my.auth.gateway.auth;

import cn.dev33.satoken.stp.StpInterface;
import com.alibaba.cloud.commons.lang.StringUtils;
import com.alibaba.nacos.shaded.com.google.gson.Gson;
import com.alibaba.nacos.shaded.com.google.gson.reflect.TypeToken;
import com.my.auth.service.entity.AuthPermission;
import com.my.auth.service.entity.AuthRole;
import com.my.auth.service.service.AuthPermissionService;
import com.my.auth.service.service.AuthRoleService;
import com.my.auth.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 自定义权限验证接口扩展
 *
 * @author: ChickenWing
 * @date: 2023/10/28
 */
@Component
public class StpInterfaceImpl implements StpInterface {
    @Autowired
    private AuthRoleService authRoleService;

    @Autowired
    private AuthPermissionService authPermissionService;

    private static final String authPermissionPrefix = "auth.permission";

    private static final String authRolePrefix = "auth.role";

    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        return getAuth(loginId.toString(), authPermissionPrefix);
    }

    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        return getAuth(loginId.toString(), authRolePrefix);
    }

    private List<String> getAuth(String loginId, String prefix) {
        String authKey = RedisUtil.buildKey(prefix, loginId);
        String authValue = RedisUtil.get(authKey);
        List<AuthRole> roleList;
        List<AuthPermission> permissionList;
        List<String> authList = new LinkedList<>();
        if (authRolePrefix.equals(prefix)) {
            if (StringUtils.isBlank(authValue)) {
                roleList = authRoleService.getRoleList(Long.valueOf(loginId));
            } else {
                roleList = new Gson().fromJson(authValue, new TypeToken<List<AuthRole>>() {
                }.getType());
            }
            authList = roleList.stream().map(AuthRole::getRoleKey).collect(Collectors.toList());
        } else if (authPermissionPrefix.equals(prefix)) {
            if (StringUtils.isBlank(authValue)){
                permissionList = authPermissionService.getPermission(Long.valueOf(loginId));
            } else {
                permissionList = new Gson().fromJson(authValue, new TypeToken<List<AuthPermission>>() {
                }.getType());
            }
            authList = permissionList.stream().map(AuthPermission::getPermissionKey).collect(Collectors.toList());
        }
        return authList;
    }

}
